<template>
	<view>
		<!-- 导航栏（与模板风格统一） -->
		<view :style="{height: titleNavHeight + statusBarHeight + 5 + 'px'}"
			style="position: fixed;z-index: 9999;top: 0;left: 0;right: 0;background-color: #ffffff;border-bottom: 1px solid #ebedf0;">
			<view :style="{height: titleNavHeight + 'px', top: statusBarHeight + 'px', width: '100%'}"
				class="nav-bar">
				<u-icon name="arrow-left" size="42" 
					style="width: 40rpx;height: 40rpx;margin-right: 20rpx;"
					@click="handleBack"></u-icon>
				<text class="text">{{ pageTitle }}</text>
			</view>
		</view>
		
		<!-- 占位高度 -->
		<view :style="{height: titleNavHeight + statusBarHeight + 5 + 'px'}"></view>
		
		<!-- Webview 核心容器 -->
		<web-view 
			v-if="validUrl"
			:src="validUrl"
			@message="handleWebviewMessage"
			@error="handleLoadError"
			style="width: 100vw;height: calc(100vh - var(--nav-height))">
		</web-view>
		
		<!-- 错误提示 -->
<!-- 		<view v-else class="error-container">
			<u-empty mode="data" icon="/static/empty.png"></u-empty>
		</view> -->
	</view>
</template>

<script>
import { getBoundingClientRect } from "@/utils";

export default {
	data() {
		const { windowWidth, statusBarHeight } = uni.getSystemInfoSync()
		const rect = getBoundingClientRect(windowWidth, statusBarHeight);
		return {
			windowWidth: windowWidth,
			statusBarHeight: statusBarHeight,
			titleNavHeight: (rect.top - statusBarHeight) * 2 + rect.height,
			
			validUrl: null  ,// 处理后的有效URL
			pageTitle: '网页预览'
		}
	},
	onLoad(options) {
		console.log(options)
		this.initWebviewUrl(options);
	},
	methods: {
		// 初始化URL参数
		initWebviewUrl(options) {
			try {
				if (options?.url) {
					const rawUrl = decodeURIComponent(options.url);
					this.pageTitle = options.title
					
					// URL有效性验证
					if (this.validateUrl(rawUrl)) {
						this.validUrl = this.formatUrlProtocol(rawUrl);
						this.setDynamicTitle(rawUrl);
						return;
					}
				}
				this.showInvalidUrlToast();
			} catch (e) {
				console.error('URL解析错误:', e);
				uni.navigateBack();
			}
		},

		// URL格式校验
		validateUrl(url) {
			return /^(https?|ftp):\/\//.test(url) || url.startsWith('/');
		},

		// 协议格式化
		formatUrlProtocol(url) {
			if (/^\/\//.test(url)) return `https:${url}`;
			if (!/^https?:/.test(url) && !url.startsWith('/')) {
				return `https://${url}`;
			}
			return url;
		},

		// 动态设置标题
		setDynamicTitle(url) {
			try {
				const host = new URL(url).hostname;
				uni.setNavigationBarTitle({ title: host || '网页内容' });
			} catch(e) {
				/* 非标准URL不处理 */
			}
		},

		// 显示错误提示
		showInvalidUrlToast() {
			uni.showToast({
				icon: 'error',
				title: '无效的网页地址',
				complete: () => setTimeout(() => uni.navigateBack(), 1500)
			});
		},

		// 返回操作
		handleBack() {
			uni.navigateBack({ delta: 1 });
		},

		// 加载失败处理
		handleLoadError(e) {
			console.error('网页加载失败:', e);
			uni.showToast({ title: '加载失败，请检查网络', icon: 'none' });
		},

		// 网页消息事件
		handleWebviewMessage(e) {
			console.log('Received webview message:', e.detail);
		}
	}
}
</script>

<style lang="less" scoped>
.nav-bar {
	position: absolute;
	display: flex;
	align-items: center;
	padding-left: 20rpx;

	.text {
		width: calc(100vw - 80px);
		color: #323233;
		font-weight: 500;
		font-size: 30rpx;
		display: flex;
		justify-content: center;
	}
}

.error-container {
	height: 80vh;
	display: flex;
	align-items: center;
	justify-content: center;
}
</style>
